package server;

import entity.Client;

import java.nio.channels.SelectionKey;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.*;

public class GpcRequestHandler {

	public static final String X_IP = "X_IP";
	public static final String X_PORT = "X_PORT";
	public static final String X_ENTITY_ID = "X_ENTITY_ID";
	public static final String X_ENTITY_NAME = "X_ENTITY_NAME";
	public static final String X_ENTITY_TYPE = "X_TYPE";
	//请求队列
	private static BlockingQueue<GpcRequest> REQUESTS = new LinkedBlockingQueue<GpcRequest>();
	private static ConcurrentMap<SelectionKey,GpcRequestObserver> observers = new ConcurrentHashMap<>();

	private static GpcRequest buildHeaders(GpcRequest rpc, Client obj) {
		rpc.setHeader(X_ENTITY_ID, obj.getUnique());
		rpc.setHeader(X_ENTITY_NAME, obj.getName());
		rpc.setHeader(X_ENTITY_TYPE, obj.getObjType());
		return rpc;
	}

	public static GpcRequest createRequest(Client obj) {
		return buildHeaders(new GpcRequest(),obj);
	}

	public static GpcRequest createRequest(Client obj, Map<String,String> Icontexts) {
		GpcRequest request = createRequest(obj);
		request.setHeaders(Icontexts);
		return request;
	}

	public static String getString(GpcRequest request) {
		StringBuilder sb = new StringBuilder();
		sb.append("{");
		for(String key:request.getHeaders().keySet()) {
			sb.append(key+":"+request.getHeaders().get(key)+", ");
		}
		return sb.toString().substring(0,sb.length()-2)+"}";
	}



	public static GpcRequest createRequest(Client obj, Map<String,String> Icontexts, Map<String,Object> params) {
		GpcRequest request = createRequest(obj,Icontexts);
		return request;
	}

	public static void collect(GpcRequest gpc) {
		try {
			if(gpc!=null)
				REQUESTS.offer(gpc,100,TimeUnit.MILLISECONDS);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	private static GpcRequest poll() {
		try {
			return REQUESTS.poll(2000, TimeUnit.MILLISECONDS);
		} catch (InterruptedException e) {
			return null;
		}
	}

	public static void addObserver(SelectionKey key , GpcRequestObserver observer) {
		System.out.println("注册观察者："+key+" 成功");
		observers.putIfAbsent(key, observer);
	}

	public static void receive(SelectionKey key,GpcRequest request) throws InterruptedException {
		if(key==null)
			return;
		observers.get(key).service(request);
	}
	
	public static void deleteObserver(SelectionKey key) {
		observers.remove(key);
	}

	public static void notifyAllObservers() {
		Iterator<GpcRequestObserver> it = observers.values().iterator();
		GpcRequest message = poll();
		if(message!=null) {
			while(it.hasNext()) {
				GpcRequestObserver obs = (GpcRequestObserver) it.next();
				obs.sendMessage(message);
			}
		}
	}
}
